package com.yun.config;

import com.yun.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
    @Autowired
    LoginService lonService;


    @Autowired
    private PersistentTokenRepository tokenRepository;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(lonService).passwordEncoder(password());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //退出
        http.logout().logoutUrl("/logout").
                logoutSuccessUrl("/test/hello").permitAll();

        //配置没有权限访问跳转自定义页面
      //  http.exceptionHandling().accessDeniedPage("/unauth.html");
        http.formLogin()   //自定义自己编写的登录页面
                .loginPage("/on.html")  //登录页面设置
                .loginProcessingUrl("/user/login")   //登录访问路径
                .defaultSuccessUrl("/success.html").permitAll()  //登录成功之后，跳转路径
                .failureUrl("/unauth.html")
                .and().authorizeRequests()               //定义哪些方法会被保护哪些不会被保护
                .antMatchers("/","/test/hello","/user/login").permitAll() //设置哪些路径可以直接访问，不需要认证
               /* .antMatchers("/find").hasAnyAuthority("admin","haha").
                 antMatchers("/findAll").hasAnyAuthority("menu:system ")
                .antMatchers("/testrole").hasAnyRole("管理员1","role2")*/
                .anyRequest().authenticated()    //除了上面定义的所有的请求 都需要被认证
                .and().csrf().disable();  //关闭csfr访问

    //失败跳转
        http.exceptionHandling().accessDeniedPage("/unauth");

        // 开启记住我功能 http.rememberMe()
        http.rememberMe()
                .tokenRepository(tokenRepository)
                .userDetailsService(lonService);

    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }
}
